package com.webside.wap.detail.controller;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;

import org.apache.activemq.leveldb.util.JsonCodec;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.webside.mongo.model.MongoRecord;
import com.webside.util.Common;
import com.webside.util.SensitivewordFilter;
import com.webside.wap.common.example.CommentExample;
import com.webside.wap.common.example.VideoExample;
import com.webside.wap.common.model.BSeries;
import com.webside.wap.common.model.RComment;
import com.webside.wap.common.service.BSeriesService;
import com.webside.wap.common.service.BVideoService;
import com.webside.wap.common.service.BdictionaryService;
import com.webside.wap.common.service.PBannerService;
import com.webside.wap.common.service.RCommentService;
import com.webside.wap.listener.BaseData;

/**
 * 电影详情页面控制器
 * @author XuanZhen XYH
 *
 */
@Controller
@Scope("prototype")
@RequestMapping(value="/wap/detail/")
public class DetailController {
	@Autowired
	public BSeriesService bSeriesService;
	@Autowired
	public BVideoService bVideoService;
	@Autowired
	public RCommentService rCommentService;
	@Autowired
	public PBannerService pBannerService;
	@Autowired
	public BdictionaryService  bdictionary;
	@Autowired
	private MongoTemplate mongoTemplate;
	
	/**
	 * 核心控制器，生成播放详情页面
	 * @param model
	 * @param seriesId
	 * @param setNum
	 * @param pageNo
	 * @return
	 * @throws Exception 
	 */
	@RequestMapping("show.html")
	public String show(Model model,@RequestParam("seriesId") Integer seriesId,@RequestParam("setNum") Integer setNum,Integer pageNo) throws Exception{
		model.addAttribute("baseImgPath", BaseData.img_base_path);
		/*
		 * 首先根据传入的seriesId和setNum可以定位video
		 */
		Map<String ,Object> condition = new HashMap<String,Object>();
		VideoExample video = new VideoExample();
		if (pageNo==null) {
			pageNo=0;
		}
		condition.put("seriesId",seriesId);
		condition.put("setNum", setNum);
		condition.put("pageNo", pageNo);
		List<VideoExample> listVideo= bVideoService.selectVideoByCondition(condition);
		System.out.println(listVideo.size());
		if(listVideo.size()==1){
			video=listVideo.get(0);
			model.addAttribute("video",video);
			System.out.println(video);
		}else{
			throw new Exception("数据有误！");
		}
		
		/*
		 * 根据传入的seriesId获取剧集列表
		 */
		condition.put("setNum", null);
		List<VideoExample> listVideoSeries= bVideoService.selectVideoByCondition(condition);
		model.addAttribute("listVideoSeries",listVideoSeries);
		
		/*
		 * 根据传入的seriesId获取该剧集的简介等信息
		 */
		BSeries bSeriesThis = bSeriesService.selectSeriesById(seriesId).get(0);
		model.addAttribute("bSeriesThis",bSeriesThis);
		System.out.println(JSON.toJSON(bSeriesThis));
		
		/*
		 * 猜你喜欢（通过传入的剧集id）先返回剧集对象
		 */
		BSeries bSeries = new BSeries();
		bSeries = bSeriesService.selectSeriesById(seriesId).get(0);//id为主键List只有一条数据
		List<BSeries> listBSeries = bSeriesService.selectMayLike(bSeries);
		model.addAttribute("listBSeries",listBSeries);
		System.out.println("listBSeries共有"+listBSeries.size()+"条数据");
		
			
		return Common.BACKGROUND_PATH + "/wap/video";
	}
	
	/**
	 *  新增评论或点赞
	 * @param type
	 * @param videoId
	 * @param parentId
	 * @param content
	 * @param childrenCount
	 * @return
	 */
	@RequestMapping("insertComment1.html")
	@ResponseBody
	public Object insertComment(String type,Integer videoId,Integer parentId,String content, String childrenCount){
		boolean a = false;
		System.out.println(type+videoId+parentId+content+childrenCount);
		String c = null;
		try {
			c = new String(content.getBytes("ISO-8859-1"),"UTF-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		System.out.println(c);
		CommentExample comment=new CommentExample();
		comment.setVideoId(videoId);
		if (parentId==null || "".equals(parentId)) {
			comment.setParentId(0);
		}else{
			comment.setParentId(parentId);		
		}
		comment.setContent(c);
		comment.setType(type);
		
		System.out.println("现在传入的type是："+type);
		comment.setStatus("1");
		Date date=new Date();
		if ("2".equals(type)) {
			if(childrenCount.equals("0") && childrenCount!=null){
				comment.setChildrenCount(1);
			}
			comment.setCreateTime(date);
			a = rCommentService.insertCommentOrLike(comment);
			System.out.println("回复+1");
			if (videoId!=null) {
				bVideoService.updateSomeCount(videoId.toString(), type, "comment_count");
				System.out.println("回复条数被更新到电影啦！");
			}
			
		}else if("1".equals(type)){
			comment.setCreateTime(date);
			a = rCommentService.insertCommentOrLike(comment);
			System.out.println("点赞+1");
			if (videoId!=null) {
				bVideoService.updateSomeCount(videoId.toString(), type, "like_count");
				System.out.println("点赞条数被更新到电影啦！");
			}
		}
		if (a) {
			System.out.println("插入纪录成功");
			return 1;
		}else
			//新增失败，返回0
			return 0;
	}
	
	
	
	/**
	 * 刷新点赞数的方法
	 * @return
	 */
	@RequestMapping(value="flusCount.html",method={RequestMethod.GET,RequestMethod.POST})
	public @ResponseBody Object selectLikeCount(@Param("videoId")Integer videoId){
		Integer count = 0;
		Map<String,Object> condition = new HashMap<>();
		condition.put("id", videoId);
		List<VideoExample> list = bVideoService.selectVideoByCondition(condition);
		count=list.get(0).getLikeCount();
		return count;
	}
	
	/**
	 * 查询评论
	 * @param model
	 * @param videoId
	 * @param pageNo
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping(value="recomments.html",method={RequestMethod.GET,RequestMethod.POST})
	public @ResponseBody Map<String,Object> showComment(Model model,@RequestParam("videoId") Integer videoId,@RequestParam("pageNo") Integer pageNo,HttpServletRequest request) throws Exception{
		//标识是否还有分页下一条数据
		String flag = null;
		int totalPage = 0;
		
		Map<String,Object> map=new HashMap<String,Object>();
		int pageSize = 6;
		Map<String,Object> p = this.getParentContent(pageNo, videoId);
		//父评论集合
		List<RComment> parentComment = (List<RComment>)p.get("parentComment");
		//父评论条数
		int totalCount = (int)p.get("totalCount");
		//总页数
		if ((totalCount%pageSize)==0) {
			totalPage = totalCount/pageSize;
		}else{
			totalPage = totalCount/pageSize+1;
		}
		/*
		 * 根据页码（从0开始）和总页数判断是否有下一页
		 */
		if (totalPage==0) {
			flag="none";
		}else{
			if ((pageNo+1)==totalPage) {
				//当前页是最后一页
				flag="last";
			}else if((pageNo+1)<totalPage){
				//还有下一页
				flag="next";
			}else{
				//页码大于最大页码数
				throw new Exception("页码越界！");
			}
		}
		//传入获取的标识
		map.put("flag",flag);
		//传入分页后父评论的集合
		map.put("parentComment", parentComment);
		
		//*****************获取子评论的方法**************
		//只获取最初的子评论。页码传0
		Map<String,Object> childrenCommentMap= this.getchildrenContent(0, parentComment);
		
		map.put("childrenCommentMap", childrenCommentMap);
		System.out.println(JSON.toJSON(map));
		return map;
	}
	
	/**
	 * 查询子评论分页数据
	 */
	@RequestMapping(value="pullChildren.html",method={RequestMethod.GET,RequestMethod.POST})
	public @ResponseBody Map<String ,Object> pull(Model model,String parentId,int pageNo,HttpServletRequest request){
		Map<String ,Object> map = new HashMap<String,Object>();
		System.out.println("进来");
		int pageSize = 3;
		CommentExample comment = new CommentExample();
		comment.setParentId(Integer.parseInt(parentId));
		comment.setBeginPage((pageNo)*pageSize);
		comment.setPageSize(pageSize);
		comment.setStatus("1");
		comment.setSort("create_time");
		
		List<RComment> list = rCommentService.selectByCondition(comment);
		SensitivewordFilter filter = new SensitivewordFilter();
		 for (int j = 0; j < list.size(); j++) {
			String content = filter.replaceSensitiveWord(list.get(j).getContent(), 1, "*");
			list.get(j).setContent(content);
		 }
		int count = rCommentService.selectCountByCondition(comment);
		System.out.println("我来查了一下并拿到了这些数据"+JSON.toJSON(list));
		map.put("list",list);
		map.put("count", count);
		return map;
	}
	/**
	 * 获取父评论的方法 
	 * @param pageNo
	 * @param videoId
	 * @return Map<String ,Object>
	 */
	private Map<String ,Object> getParentContent(Integer pageNo,Integer videoId){
		Map<String ,Object> parent = new HashMap<String ,Object>();
		int pageSize = 6;
		CommentExample comment = new CommentExample();
		
		comment.setBeginPage(pageNo*pageSize);
		comment.setVideoId(videoId);
		comment.setPageSize(pageSize);
		comment.setType("2");
		comment.setParentId(0);
		comment.setStatus("1");
		comment.setSort("create_time");
		
		List<RComment> parentComment = rCommentService.selectByCondition(comment);
		SensitivewordFilter filter = new SensitivewordFilter();
		for(int i = 0;i<parentComment.size();i++){
			String content = filter.replaceSensitiveWord(parentComment.get(i).getContent(), 1, "*");
			parentComment.get(i).setContent(content);
		}
		parent.put("parentComment", parentComment);
		
		//查询符合条件的总条数
		int totalCount = rCommentService.selectCountByCondition(comment);
		parent.put("totalCount", totalCount);
		
		return parent;
	}

	/**
	 * 获取子评论的方法
	 * @param pageNo
	 * @param videoId
	 * @param parentComment
	 * @return Map<String,Object> children
	 */
	private Map<String,Object> getchildrenContent(Integer pageNo,List<RComment> parentComment){
		Map<String, Object> children = new HashMap<String,Object>();
		RComment rComment = new RComment();
		int parentId = 0;
		int pageSize = 3; 
		int count =0; 
		List<RComment> childrenComment = new ArrayList<RComment>();
		CommentExample commentChild = new CommentExample();
		
		for (int i = 0; i < parentComment.size(); i++) {
			 rComment = parentComment.get(i);
			 parentId = rComment.getId();
			 
			 commentChild.setParentId(parentId);
			 commentChild.setBeginPage(pageNo*pageSize);
			 commentChild.setPageSize(pageSize);
			 commentChild.setStatus("1");
			 commentChild.setSort("create_time");
			 //查询对应子评论
			 childrenComment  = rCommentService.selectByCondition(commentChild);
			 count = rCommentService.selectCountByCondition(commentChild);
			 //过滤敏感词
			 SensitivewordFilter filter = new SensitivewordFilter();
			 for (int j = 0; j < childrenComment.size(); j++) {
				String content = filter.replaceSensitiveWord(childrenComment.get(j).getContent(), 1, "*");
				childrenComment.get(j).setContent(content);
			 }
			 children.put(""+i, childrenComment);
			 children.put("count"+i, count);
		}
		
		return children;
	}
	
	@RequestMapping(method = RequestMethod.POST, value = "/addRecord.html")
	@ResponseBody
	public void getStatisticsRecord(MongoRecord mongoRecord, HttpServletRequest request) {
		try {
			System.out.println("进来");
			// 调用java自带的uuid生成唯一标示id
			UUID uuid = UUID.randomUUID();
			// 去掉不需要的字符
			String id = uuid.toString().replaceAll("\\-", "");
			// 为实体对象加入标示id
			mongoRecord.setId(id);
			mongoRecord.setIp(Common.toIpAddr(request));
			mongoTemplate.insert(mongoRecord, "play_records");

		} catch (Exception e) {
			e.printStackTrace();

		}

	}
}
